// ~/middleware/auth.global.ts (全局中间件)
import { useUserStore } from '@/store'
import tool from '@/utils/tool'
import NProgress from 'nprogress';

const whiteRoute = ['login', 'mineDoc', 'interfaceList', 'interfaceCode', 'signature', '/error']

export default defineNuxtRouteMiddleware(async (to,from) => {
  console.log('from: ', from);
  const userStore = useUserStore()
  const config = useRuntimeConfig()
  const token = tool.local.get(config.public.VITE_APP_TOKEN_PREFIX)
  const defaultRoutePath = '/dashboard'
  // 进度条处理
  if (process.client) {
    NProgress.start()
  }
  // 登录状态处理
  if (token) {
    console.log('t')
    if (to.name === 'login' || to.name === 'index' ) {
      return navigateTo(defaultRoutePath)
    }

    let allRouters = userStore.routers;
    if (!userStore.user) {
      const data = await userStore.requestUserInfo()
      allRouters = userStore.routers
      if (data) {
        return navigateTo(to.fullPath)
      }
    }
    const all:string[] = []
    allRouters && allRouters.forEach(({children, path}:any)=>{
      if (children.length === 0) {
        all.push(path)
      }
      children.forEach((item:any)=>{
        all.push(item.path)
      })
    })

    if(!all.includes(to.path) && !whiteRoute.includes(to.path)) {
      // return navigateTo('/error')
      return navigateTo({
        path: '/error',
        query: { redirect: from.fullPath }
      })
    }

  } else {
    if (!whiteRoute.includes(to.name as string)) {
      return navigateTo({
        name: '/',
        query: { redirect: to.fullPath }
      })
    }
  }
})
